package com.eonmind.common.security.aop;

import cn.dev33.satoken.stp.StpUtil;
import com.eonmind.common.contract.data.response.ResponseEntity;
import com.eonmind.user.contract.api.UserFeignService;
import com.eonmind.user.contract.dto.UserInfoData;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * @author Xujie
 * @since 2025/4/25 23:56
 **/
@Aspect
@Component
public class UserInfoAop {
    @Resource
    private UserFeignService userFeignService;
    @Around("@annotation(com.eonmind.common.security.annotations.UserInfo)")
    public Object handleMyAnnotation(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        // 找到对应用户的参数
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof UserInfoData) {
                args[i] = getUserInfoData();
            }
        }
        Object result;
        try {
            result = joinPoint.proceed(args);
        } catch (Exception e) {
            throw e;
        }
        return result;
    }

    private UserInfoData getUserInfoData() {
        // 模拟获取用户信息
        Long loginIdAsLong = StpUtil.getLoginId(0L);
        ResponseEntity<UserInfoData> userInfoDataResponseEntity = userFeignService.queryUserInfoById(loginIdAsLong);
        UserInfoData userInfoData = null;
        if(Boolean.TRUE.equals(userInfoDataResponseEntity.getStatus())) {
            userInfoData = userInfoDataResponseEntity.getData();
        }
        return userInfoData;
    }
}
